package aufgabe02;

public class LinkedList implements IList
{
  private StackList list;
  
  public LinkedList()
  {
    list = new StackList();
  }
  
  public void clear()
  {
    list.clear();
  }

  public int getAt(int index)
  {
    if(index < 0 || index >list.getCount())
      throw new IndexOutOfBoundsException();
    
    Node node = list.lastNode;
    for(int i = 0; i<index; i++)
      node = node.prev;
    return node.value;
  }

  public int getCount()
  {
    return list.getCount();
  }

  public void insertAt(int index, int value)
  {
    if(index == 0)
      list.push(value);
    else if(index <= list.getCount() && index >= 0)
    {
      Node node = null;
      Node prevNode = list.lastNode;
      for(int i = 0; i<index; i++)
      {
        node = prevNode;
        prevNode = node.prev;
      }
      Node newNode = new Node();
      newNode.prev = prevNode;
      newNode.value = value;      
      
      node.prev = newNode;
      list.size++;      
    }
    else
      throw new IndexOutOfBoundsException();
  }
  
  public void removeAt(int index)
  {
    if(index == 0)
      list.pop();
    else if(index <= list.getCount() && index >= 0)
    {
      Node subsNode = list.lastNode;
      for(int i = 1; i<index; i++)
        subsNode = subsNode.prev;
      subsNode.prev = subsNode.prev.prev;
      list.size--;
    }
    else
      throw new IndexOutOfBoundsException();
  }

  public int search(int value)
  {
    Node node = list.lastNode;
    int index = 0;
    while(node != null)
    {
      if(node.value == value)
        return index;
      node = node.prev;
      index++;
    }
    throw new RuntimeException();
  }
  
  public String toString()
  {
    Node node = list.lastNode;
    String ausgabe = "Index    Wert\n"+
                     "-------------\n";
    int count = 0;
    while(node != null)
    {
      ausgabe += String.format("%2d", count)+" "+String.format("%10d", node.value)+"\n";
      node = node.prev;
      count++;
    }
    return ausgabe;
  }
}
